import { fetchData } from '.';
import * as cheerio from 'cheerio';
export async function scrapePoemTagId(
  url: string,
): Promise<{ name: string; url: string; type: string }[]> {
  try {
    const html: string | Buffer = await fetchData(url);
    if (html) {
      const $ = cheerio.load(html);

      const results = [];
      const mainElement = $('main.mt-4.space-y-8.p-4'); // 获取目标节点
      mainElement.children('div').each((index, element) => {
        const type = $(element).find('h2').text().trim();
        $(element)
          .find('p[prose-p]')
          .children('a')
          .map((i, e) => {
            results.push({
              name: $(e).text().trim(),
              url: $(e).attr('href'),
              type,
            });
          });
      });

      // eslint-disable-next-line @typescript-eslint/no-unsafe-return
      return results;
    }
  } catch (error) {
    throw Error(error);
  }
}

export async function scrapePoemTagDesc(
  url: string,
): Promise<{ name: string; description: string }> {
  try {
    const html: string | Buffer = await fetchData(url);
    if (html) {
      const $ = cheerio.load(html);

      const mainElement = $('h1.prose-h1'); // 获取目标节点
      const desc = mainElement.next().text().trim();

      // eslint-disable-next-line @typescript-eslint/no-unsafe-return
      return {
        name: mainElement.text().trim(),
        description: desc || null,
      };
    }
  } catch (error) {
    throw Error(error);
  }
}
